import cloneDeep from 'lodash/cloneDeep'

// 扁平数据填充成树级
export const genarateTree = function(list) {
  const _list = cloneDeep(list)
  return _list.reduce((r, o, i) => {
    if (!o.parentid) {
      r.push(o)
    } else {
      _insertParent(r, o)
    }
    return r
  }, [])
}

function _insertParent(list, child) {
  list.forEach((o, i) => {
    if (o.id === child.parentid) {
      if (!o.children) {
        o.children = []
      }
      o.children.push(child)
    } else if (o.children) {
      _insertParent(o.children, child)
    }
  })
}

// 清除子级空数据
export const destroyEmptyChild = function(list) {
  list.forEach(o => {
    if (o.child) {
      if (!o.child.length) {
        delete o.child
      } else {
        destroyEmptyChild(o.child)
      }
    }
  })
}

// 级联转换数据
export const convertData = function(list) {
  return _convertChildData(list.reduce((r, o) => {
    if (o.level === 1) {
      if (o.children && o.children.length) {
        o.children = _filterCheckedChild(o.children)
      }
      r.push(o)
    } else if (!_checkChildIsExist(r, o.value)) {
      if (o.parent) {
        // 取到根级父节点
        let rootParent = null
        let temp = o
        while (temp.level !== 1) {
          rootParent = o.parent
          temp = o.parent
        }
        // 过滤出选中的子节点
        rootParent.children = _filterCheckedChild(rootParent.children)
        r.push(rootParent)
      }
    }
    return r
  }, []))
}

// 过滤选中子级
function _filterCheckedChild(child) {
  return child.reduce((r, o) => {
    if (o.checked) {
      r.push(o)
    }
    if (o.children && o.children.length) {
      o.children = _filterCheckedChild(o.children)
    }
    return r
  }, [])
}

// 查找子级是否存在...中
function _checkChildIsExist(list, id) {
  return list.reduce((r, o) => {
    if (o.value === id) {
      r = true
    } else if (o.children && o.children.length) {
      r = _checkChildIsExist(o.children, id)
    }
    return r
  }, false)
}

// 级联填充选中树
function _convertChildData(list) {
  return list.map(o => {
    const res = {
      // name: '',
      // code: ''
    }
    if (o.label && o.checked) {
      res['name'] = o.label
    }
    if (o.label && o.checked) {
      res['code'] = o.value
    }
    const child = o.children
    if (child && child.length) {
      res.child = _convertChildData(child)
    }
    return res
  })
}
